<template>
  <div class="email-mass-messaging-container">
    <el-row :gutter="20">
      <!-- Left side: Email Editor -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card shadow="hover" class="message-editor-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-edit-outline"></i>
              <span>邮件内容</span>
            </div>
            <div class="header-actions">
              <el-button type="text" icon="el-icon-delete" @click="clearMessage">清空</el-button>
              <el-button type="text" icon="el-icon-time" @click="showHistoryDialog">历史任务</el-button>
            </div>
          </div>

          <el-form :model="messageForm" :rules="formRules" ref="messageForm" label-width="100px">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="messageForm.taskName" placeholder="请输入任务名称" clearable></el-input>
            </el-form-item>

            <el-form-item label="邮件模版" prop="templateId">
              <div class="template-selector">
                <el-input v-model="selectedTemplateName" placeholder="请从模版库选择邮件模版" readonly style="width: calc(100% - 110px)"></el-input>
                <el-button type="primary" size="small" @click="showTemplateDialog">从模版库选择</el-button>
              </div>
            </el-form-item>

            <el-form-item label="发件箱" prop="emailSenderId">
              <el-select v-model="messageForm.emailSenderId" placeholder="请选择发件箱" clearable style="width: 100%">
                <el-option
                  v-for="sender in senderList"
                  :key="sender.id"
                  :label="`${sender.sendName} (${sender.sendEmail})`"
                  :value="sender.id">
                  <div class="sender-option">
                    <div class="sender-name">{{ sender.sendName }}</div>
                    <div class="sender-email">{{ sender.sendEmail }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="邮件主题" prop="emailSubject">
              <el-input v-model="messageForm.emailSubject" placeholder="请输入邮件主题"></el-input>
            </el-form-item>

            <el-form-item label="邮件内容" prop="emailContent">
              <editor v-model="messageForm.emailContent" :min-height="300" />
            </el-form-item>

             <el-form-item label="邮件附件" prop="attachments">
                <FileUpload v-model="messageForm.attachments" />
            </el-form-item>

            <el-form-item label="接收人" prop="recipientType">
              <el-radio-group v-model="messageForm.recipientType" @change="handleRecipientTypeChange">
                <el-radio label="group">选择分组</el-radio>
                <el-radio label="upload">导入地址</el-radio>
                <el-radio label="manual">手动输入</el-radio>
              </el-radio-group>

              <!-- Recipient Inputs -->
              <div v-if="messageForm.recipientType === 'group'">
                <el-button type="primary" @click="showContactDialog">选择联系人</el-button>
                <div v-if="selectedContacts.length > 0" class="selected-contacts-preview">
                  <el-tag
                    v-for="contact in selectedContacts.slice(0, 5)"
                    :key="contact.customerId"
                    type="info"
                    size="small"
                    style="margin: 2px;"
                  >{{ contact.customerName }}</el-tag>
                  <span v-if="selectedContacts.length > 5" class="more-contacts">
                    等{{ selectedContacts.length }}个联系人
                  </span>
                </div>
              </div>
              <div v-if="messageForm.recipientType === 'upload'">
                <el-upload action="#" :http-request="handleFileUpload" :file-list="fileList" :limit="1" accept=".xls,.xlsx">
                  <el-button size="small" type="primary">选择文件</el-button>
                   <div slot="tip" class="el-upload__tip">支持xls、xlsx格式，<el-button type="text" size="small" @click.stop="downloadEmailTemplate">下载模版</el-button></div>
                </el-upload>
              </div>
              <div v-if="messageForm.recipientType === 'manual'">
                <el-input type="textarea" :rows="5" placeholder="请输入邮箱地址，多个地址请用英文逗号或换行分隔" v-model="manualRecipients"></el-input>
              </div>
               <div class="recipient-info">已选择 <span class="count">{{ recipientCount }}</span> 个联系人</div>
            </el-form-item>

             <!-- 定时发送 -->
             <el-form-item label="定时发送" prop="scheduledTime">
              <div class="schedule-selector">
                <el-date-picker
                  v-model="messageForm.scheduledTime"
                  type="datetime"
                  placeholder="请选择发送时间"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </div>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 最近发送记录
        <el-card shadow="hover" class="history-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-time"></i>
              <span>最近发送记录</span>
            </div>
            <div class="header-actions">
              <el-button type="text" @click="viewAllHistory">查看全部</el-button>
            </div>
          </div>

          <div class="history-list">
            <el-table
              :data="sendHistory"
              style="width: 100%"
              :show-header="false"
              size="small"
            >
              <el-table-column width="80">
                <template slot-scope="scope">
                  <el-tag
                    size="mini"
                    :type="getTaskStatusType(scope.row.taskStatus)"
                  >{{ getTaskStatusText(scope.row.taskStatus) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="scope">
                  <div class="history-item">
                    <div class="history-title">{{ scope.row.taskName }}</div>
                    <div class="history-info">
                      <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                      <span>{{ scope.row.totalCount || 0 }}人</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column width="60">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="loadTaskData(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>-->
      </el-col>

      <!-- Right side: Sending Options -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card shadow="hover" class="sending-options-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-s-data"></i>
              <span>发送统计</span>
            </div>
          </div>
          <el-form label-width="100px">
            <!-- 发送统计 -->

                <div class="stats-content">
                  <div class="stat-row">
                    <span class="stat-label">接收人数</span>
                    <span class="stat-value">{{ recipientCount }}</span>
                  </div>
                  <div class="stat-row">
                    <span class="stat-label">消息条数</span>
                    <span class="stat-value">{{ recipientCount }}</span>
                  </div>
                  <div class="stat-row">
                    <span class="stat-label">每条价格</span>
                    <span class="stat-value price">¥ 0.006</span>
                  </div>
                  <div class="stat-row total">
                    <span class="stat-label">预计费用</span>
                    <span class="stat-value price-total">¥ {{ (recipientCount * 0.006).toFixed(2) }}</span>
                  </div>
                </div>

              <div class="action-buttons">
                <el-button
                  type="primary"
                  @click="submitForm"
                  :loading="sending"
                  class="timed-send-btn"
                  size="mini"
                >
                  <i class="el-icon-s-promotion"></i>
                  定时发送
                </el-button>
                <el-button
                  type="info"
                  @click="saveDraft"
                  :loading="saving"
                  class="draft-btn"
                  size="mini"
                >
                  <i class="el-icon-document"></i>
                  暂存任务
                </el-button>
              </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 模板选择对话框 -->
    <el-dialog title="选择邮件模板" :visible.sync="templateDialogVisible" width="800px" append-to-body>
      <el-form :model="templateQueryParams" ref="templateQueryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="templateQueryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter.native="getTemplateList"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getTemplateList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetTemplateQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="templateLoading" :data="templateDialogList" height="400px">
        <el-table-column label="模板编码" prop="id" show-overflow-tooltip width="180" v-if="false"/>
        <el-table-column label="模板名称" prop="templateName" show-overflow-tooltip width="180"/>
        <el-table-column label="邮件主题" prop="templateTitle" show-overflow-tooltip width="200"/>
        <el-table-column label="模板分组" prop="templateGroupName" width="120"/>
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="selectTemplate(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="templateTotal > 0"
        :total="templateTotal"
        :page.sync="templateQueryParams.pageNum"
        :limit.sync="templateQueryParams.pageSize"
        @pagination="getTemplateList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="templateDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 联系人选择对话框 -->
    <el-dialog title="选择联系人" :visible.sync="contactDialogVisible" width="1200px" append-to-body>
      <el-row :gutter="20">
        <!-- 左侧：客户分组树 -->
        <el-col :span="6">
          <el-card shadow="never" class="group-tree-card">
            <div slot="header" class="card-header">
              <span>客户分组</span>
            </div>
            <el-tree
              :data="contactGroupTreeData"
              :props="contactTreeProps"
              node-key="groupId"
              default-expand-all
              highlight-current
              @node-click="handleContactGroupClick"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span class="node-label">
                  <i v-if="data.groupId == 0" class="el-icon-s-home tree-icon" />
                  <i v-else class="el-icon-folder tree-icon" />
                  {{ data.groupName }}
                </span>
              </span>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 右侧：客户列表 -->
        <el-col :span="18">
          <el-card shadow="never" class="contact-list-card">
            <div slot="header" class="card-header">
              <span>{{ currentContactGroupName }}</span>
              <div>
                <el-input
                  v-model="contactQueryParams.customerName"
                  placeholder="搜索客户姓名"
                  clearable
                  size="small"
                  style="width: 200px; margin-right: 10px"
                  @keyup.enter.native="getContactList"
                />
                <el-button type="primary" size="small" @click="getContactList">搜索</el-button>
              </div>
            </div>

            <el-table
              ref="contactTable"
              v-loading="contactLoading"
              :data="contactList"
              @selection-change="handleContactSelectionChange"
              height="400px"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="客户姓名" prop="customerName" width="120" />
              <el-table-column label="邮箱地址" prop="email" min-width="200" />
              <el-table-column label="客户分组" prop="groupName" width="120" />
              <el-table-column label="创建时间" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="contactTotal > 0"
              :total="contactTotal"
              :page.sync="contactQueryParams.pageNum"
              :limit.sync="contactQueryParams.pageSize"
              @pagination="getContactList"
            />
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <span style="float: left; line-height: 32px;">
          已选择 <span style="color: #409EFF; font-weight: bold;">{{ selectedContacts.length }}</span> 个联系人
        </span>
        <el-button @click="contactDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmContactSelection">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 历史任务对话框 -->
    <el-dialog title="历史任务" :visible.sync="historyDialogVisible" width="1000px" append-to-body>
      <el-form :model="historyQueryParams" ref="historyQueryForm" size="small" :inline="true">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="historyQueryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter.native="getHistoryList"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getHistoryList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetHistoryQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="historyLoading" :data="historyList" height="400px">
        <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip width="200"/>
        <el-table-column label="邮件主题" prop="emailSubject" show-overflow-tooltip width="180"/>
        <el-table-column label="任务状态" prop="taskStatus" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.taskStatus)">{{ getStatusText(scope.row.taskStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="接收数/成功/失败" align="center" width="150">
          <template slot-scope="scope">
            <span class="stat-number">{{ scope.row.totalCount || 0 }}</span> /
            <span class="stat-number success">{{ scope.row.successCount || 0 }}</span> /
            <span class="stat-number error">{{ scope.row.failCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="loadHistoryTask(scope.row)">加载</el-button>
            <el-button size="mini" type="text" @click="copyHistoryTask(scope.row)">复制</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="historyTotal > 0"
        :total="historyTotal"
        :page.sync="historyQueryParams.pageNum"
        :limit.sync="historyQueryParams.pageSize"
        @pagination="getHistoryList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmailTemplate } from '@/api/email/emailtemplate';
import {listEmailManage} from '@/api/email/EmailManage';
import { listEmailTask, getEmailTask, delEmailTask, addEmailTask } from '@/api/email/emailTask';
import {
  listContactCustomer,
  getContactCustomer,
  addContactCustomer,
  updateContactCustomer,
  delContactCustomer,
  exportContactCustomer,
  batchUpdateCustomerGroup,
  searchCustomers,
  checkPhoneUnique,
  importContactCustomer,
  downloadImportTemplate
} from "@/api/Sms/contactCustomer";
import {
  listContactGroup,
  treeSelectContactGroup,
  getContactGroup,
  addContactGroup,
  updateContactGroup,
  delContactGroup
} from "@/api/Sms/contactGroup";
import Editor from '@/components/Editor';
import FileUpload from '@/components/FileUpload';
import { getToken } from '@/utils/auth';

export default {
  name: "EmailMassMessaging",
  components: {
    Editor,
    FileUpload
  },
  data() {
    return {
      messageForm: {
        taskName: '',
        templateId: '',
        emailSenderId: '',
        emailSubject: '',
        emailContent: '',
        attachments: [],
        recipientType: 'group',
        recipientGroup: ''
      },
      formRules: {
        taskName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        emailSenderId: [
          { required: true, message: '发件箱不能为空', trigger: 'change' }
        ],
        emailSubject: [
          { required: true, message: '邮件主题不能为空', trigger: 'blur' }
        ],
        emailContent: [
          { required: true, message: '邮件内容不能为空', trigger: 'blur' }
        ],
        templateId:[
          { required: true, message: '邮件模版不能为空', trigger: 'change' }
        ],
        scheduledTime: [
          { required: true, message: '定时时间不能为空', trigger: 'blur' }
        ],
        recipients: [
          { required: true, message: '请选择收件人', trigger: 'change' },
          { validator: this.validateRecipients, trigger: 'change' }
        ]
      },
              sendType: 'timed',
      sending: false,
      saving: false,
      recipientCount: 0,
      manualRecipients: '',
      uploadedEmails: [],
      fileList: [],
      selectedContacts: [],

      // 发送历史
      sendHistory: [],

      // 模板选择相关
      templateDialogVisible: false,
      templateDialogList: [],
      templateLoading: false,
      templateTotal: 0,
      templateQueryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null
      },
      selectedTemplateName: '',

      // 发件箱列表
      senderList: [],

      // 联系人选择相关
      contactDialogVisible: false,
      contactGroupTreeData: [],
      contactTreeProps: {
        children: 'children',
        label: 'groupName'
      },
      currentContactGroupId: null,
      currentContactGroupName: '全部联系人',
      contactList: [],
      contactLoading: false,
      contactTotal: 0,
      contactQueryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        groupId: null
      },
      
      // 防止选择变化时的无限循环
      isRestoringSelection: false,
      // 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      },
      // 历史任务相关
      historyDialogVisible: false,
      historyList: [],
      historyLoading: false,
      historyTotal: 0,
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        createUserid: null
      }
    };
  },
  computed: {
  },
  created() {
    this.getSenderList();
    this.getContactGroupTree();
    this.getHistoryEmailTask();
    // 初始化定时发送时间
    this.initScheduledTime();
  },
      methods: {
      // 初始化定时发送时间
      initScheduledTime() {
        const now = new Date();
        const scheduledTime = new Date(now.getTime() + 2 * 60 * 1000);
        const year = scheduledTime.getFullYear();
        const month = String(scheduledTime.getMonth() + 1).padStart(2, '0');
        const day = String(scheduledTime.getDate()).padStart(2, '0');
        const hours = String(scheduledTime.getHours()).padStart(2, '0');
        const minutes = String(scheduledTime.getMinutes()).padStart(2, '0');
        this.messageForm.scheduledTime = `${year}-${month}-${day} ${hours}:${minutes}:00`;
      },

      // 获取发件箱列表
      getSenderList() {
      listEmailManage({ auditStatus: 1, status: 0 ,createUserid : this.$store.getters.userId}).then(response => {
        this.senderList = response.rows || [];
      });
    },

    // 获取历史邮件任务
    getHistoryEmailTask() {
      listEmailTask({ createUserid: this.$store.getters.userId, pageSize: 5 }).then(response => {
        this.sendHistory = response.rows || [];
      });
    },

    // 查看全部发送历史
    viewAllHistory() {
      this.$router.push({
        name: 'EmailBulkTask'
      });
    },

    // 加载任务数据
    loadTaskData(task) {
      this.clearMessage(); // 重置表单

      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '正在加载任务数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 调用API获取任务详情
      getEmailTask(task.taskId).then(response => {
        if (response.code === 200) {
          const taskData = response.data;

          // 填充邮件内容
          this.messageForm.taskName = taskData.taskName;
          this.messageForm.temp = taskData.emailSubject;
          this.messageForm.emailSubject = taskData.emailSubject;
          this.messageForm.emailContent = taskData.emailContent;

          this.messageForm.attachments = taskData.attachments ? JSON.parse(taskData.attachments) : [];

          // 处理模板
          if (taskData.templateId) {
            this.messageForm.templateId = taskData.templateId;
            // 查找模板名称
            const template = this.templateDialogList.find(t => t.templateId === taskData.templateId);
            if (template) {
              this.selectedTemplateName = template.templateName;
            }
          }

          // 设置为分组模式并加载接收人
          this.messageForm.recipientType = 'group';
          if (taskData.recipients && taskData.recipients.length > 0) {
            this.selectedContacts = taskData.recipients;
            this.recipientCount = this.selectedContacts.length;
          }

          // 处理定时发送
          if (taskData.scheduledTime) {
            this.sendType = 'timed';
            this.scheduledTime = new Date(taskData.scheduledTime);
            this.scheduledTimeDisplay = this.formatDateTime(this.scheduledTime);
          } else {
            this.sendType = 'now';
            this.scheduledTime = null;
            this.scheduledTimeDisplay = '';
          }

          // 滚动到页面顶部
          window.scrollTo(0, 0);

          this.$message.success('任务数据加载成功');
        } else {
          this.$message.error('加载任务数据失败: ' + response.msg);
        }
        loading.close();
      }).catch(error => {
        console.error('加载任务数据失败', error);
        this.$message.error('加载任务数据失败，请稍后再试');
        loading.close();
      });
    },

    // 获取任务状态类型
    getTaskStatusType(status) {
      const statusTypeMap = {
        '0': 'info',    // 草稿
        '1': 'warning', // 待发送
        '2': 'primary', // 发送中
        '3': 'success', // 已完成
        '4': 'info'     // 已取消
      };
      return statusTypeMap[status] || 'info';
    },

    // 获取任务状态文本
    getTaskStatusText(status) {
      const statusTextMap = {
        '0': '草稿',
        '1': '待发送',
        '2': '发送中',
        '3': '已完成',
        '4': '已取消'
      };
      return statusTextMap[status] || '未知';
    },

    // 模板选择相关方法
    showTemplateDialog() {
      this.templateDialogVisible = true;
      this.getTemplateList();
    },
    getTemplateList() {
      this.templateLoading = true;
      return listEmailTemplate(this.templateQueryParams).then(response => {
        this.templateDialogList = response.rows;
        this.templateTotal = response.total;
        this.templateLoading = false;
        return response;
      }).catch(error => {
        this.templateLoading = false;
        throw error;
      });
    },
    resetTemplateQuery() {
      this.templateQueryParams = {
        pageNum: 1,
        pageSize: 10,
        templateName: null
      };
      this.getTemplateList();
    },
    selectTemplate(row) {
      this.messageForm.templateId = row.id;
      this.selectedTemplateName = row.templateName;
      this.messageForm.emailSubject = row.templateTitle;
      this.messageForm.emailContent = row.templateHtml;

      // 自动生成任务名称
      const now = new Date();
      const dateStr = now.getFullYear() +
                     String(now.getMonth() + 1).padStart(2, '0') +
                     String(now.getDate()).padStart(2, '0');
      if (!this.messageForm.taskName) {
        this.messageForm.taskName = `${dateStr}_${row.templateName}`;
      }

      this.templateDialogVisible = false;
      this.$message.success('模板选择成功');
    },

    // 发送类型变化处理（保留方法以防其他地方调用）
    handleSendTypeChange() {
      // 始终为定时发送，重新设置时间
      this.initScheduledTime();

      // 当发送类型改变时，重新验证相关字段
      this.$nextTick(() => {
        this.$refs.messageForm.validateField('templateId');
        this.$refs.messageForm.validateField('scheduledTime');
      });
    },

    // 格式化日期时间显示（用户友好格式，不显示秒）
    formatDateTime(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:00`;
    },

    // 格式化时间显示（用于用户提示信息，不显示秒）
    formatTimeForDisplay(timeString) {
      if (!timeString) return '';
      // 如果已经是字符串格式 yyyy-MM-dd HH:mm:ss，则截取前16位
      if (typeof timeString === 'string' && timeString.length >= 16) {
        return timeString.substring(0, 16);
      }
      return timeString;
    },

    // 清空消息
    clearMessage() {
      this.$refs.messageForm.resetFields();
      this.selectedTemplateName = '';
      this.selectedContacts = [];
      this.manualRecipients = '';
      this.uploadedEmails = [];
      this.fileList = [];
      this.recipientCount = 0;
      this.sendType = 'timed';
      // 重新初始化定时发送时间
      this.initScheduledTime();
      
      // 清空联系人表格选择状态
      if (this.$refs.contactTable) {
        this.$refs.contactTable.clearSelection();
      }
    },

    // 接收人类型变化
    handleRecipientTypeChange() {
      this.updateRecipientCount();
      
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.messageForm.validateField('recipients');
      });
    },

    // 更新接收人数量
    async updateRecipientCount() {
      if (this.messageForm.recipientType === 'group') {
        this.recipientCount = this.selectedContacts.length;
      } else if (this.messageForm.recipientType === 'upload') {
        this.recipientCount = this.uploadedEmails.length;
      } else if (this.messageForm.recipientType === 'manual') {
        this.recipientCount = this.manualRecipients.split(/[\n,]+/).filter(email => email.trim()).length;
      } else {
        this.recipientCount = 0;
      }
    },

    // 文件上传处理
    handleFileUpload(file) {
      // 这里应该解析Excel文件并提取邮箱地址
      // 暂时模拟处理
      this.uploadedEmails = ['example1@email.com', 'example2@email.com'];
      this.updateRecipientCount();
    },

    // 下载邮件模板
    downloadEmailTemplate() {
      // 下载邮件导入模板
      this.$message.info('下载模板功能待实现');
    },

    // 暂存草稿
    saveDraft() {
      this.saving = true;
      const taskData = {
        templateId : this.messageForm.templateId,
        taskName: this.messageForm.taskName,
        emailSenderId: this.messageForm.emailSenderId,
        emailSubject: this.messageForm.emailSubject,
        emailContent: this.messageForm.emailContent,
        attachments: JSON.stringify(this.messageForm.attachments),
        taskStatus: '0', // 草稿状态
        sendType: this.sendType,
        scheduledTime: this.messageForm.scheduledTime,
        recipientType: this.messageForm.recipientType,
        recipients: this.getRecipients()
      };

      addEmailTask(taskData).then(() => {
        this.$modal.msgSuccess("草稿保存成功");
        this.saving = false;
        // 刷新历史记录
        this.getHistoryEmailTask();
      }).catch(() => {
        this.saving = false;
      });
    },

    // 获取接收人列表
    getRecipients() {
      if (this.messageForm.recipientType === 'group') {
        return this.selectedContacts.map(contact => ({
          email: contact.email,
          customerName: contact.customerName
        }));
      } else if (this.messageForm.recipientType === 'upload') {
        return this.uploadedEmails.map(email => ({ email: email }));
      } else if (this.messageForm.recipientType === 'manual') {
        return this.manualRecipients.split(/[\n,]+/).map(e => e.trim()).filter(e => e).map(email => ({ email: email }));
      }
      return [];
    },

    // 提交表单
    submitForm() {
      this.$refs.messageForm.validate(valid => {
        if (valid) {
          this.sending = true;
          const taskData = {
            templateId : this.messageForm.templateId,
            taskName: this.messageForm.taskName,
            emailSenderId: this.messageForm.emailSenderId,
            emailSubject: this.messageForm.emailSubject,
            emailContent: this.messageForm.emailContent,
            attachments: JSON.stringify(this.messageForm.attachments),
            taskStatus: '1', // 待发送状态
            sendType: this.sendType,
            scheduledTime: this.messageForm.scheduledTime,
            recipientType: this.messageForm.recipientType,
            recipients: this.getRecipients()
          };

          addEmailTask(taskData).then(() => {
            this.$modal.msgSuccess("定时发送任务创建成功，将在 " + this.formatTimeForDisplay(this.messageForm.scheduledTime) + " 发送");
            this.sending = false;
            this.clearMessage();
            // 刷新历史记录
            this.getHistoryEmailTask();
          }).catch(() => {
            this.sending = false;
          });
        }
      });
    },

    // 联系人选择相关方法
    getContactGroupTree() {
      listContactGroup({}).then(response => {
        const groups = response.data || [];
        const tree = this.handleTree(groups, 'groupId', 'parentId');
        this.contactGroupTreeData = [{ groupId: 0, groupName: '全部联系人', children: tree }];
      });
    },
    showContactDialog() {
      console.log('showContactDialog 被调用，当前selectedContacts:', this.selectedContacts);
      this.contactDialogVisible = true;
      this.getContactList();
    },
    handleContactGroupClick(data) {
      if (data.groupId === 0) {
        this.currentContactGroupId = null;
        this.currentContactGroupName = '全部联系人';
      } else {
        this.currentContactGroupId = data.groupId;
        this.currentContactGroupName = data.groupName;
      }
      this.contactQueryParams.groupId = this.currentContactGroupId;
      this.contactQueryParams.pageNum = 1;
      this.getContactList();
    },
    getContactList() {
      this.contactLoading = true;
      listContactCustomer(this.contactQueryParams).then(response => {
        this.contactList = response.rows;
        this.contactTotal = response.total;
        this.contactLoading = false;

        // 数据加载完成后，延迟恢复已选择的联系人状态
        setTimeout(() => {
          this.restoreContactSelection();
        }, 100);
      });
    },
    handleContactSelectionChange(selection) {
      console.log('handleContactSelectionChange 被调用，当前选择:', selection);
      console.log('之前的selectedContacts:', this.selectedContacts);
      
      // 获取当前页面的联系人ID列表
      const currentPageContactIds = this.contactList.map(contact => contact.customerId);
      console.log('当前页面联系人ID:', currentPageContactIds);

      // 保留不在当前页面的已选择联系人
      const contactsNotInCurrentPage = this.selectedContacts.filter(contact =>
        !currentPageContactIds.includes(contact.customerId)
      );
      console.log('不在当前页面的已选联系人:', contactsNotInCurrentPage);

      // 合并当前页面的选择和其他页面的选择
      this.selectedContacts = [...contactsNotInCurrentPage, ...selection];
      console.log('合并后的selectedContacts:', this.selectedContacts);
      
      // 更新接收人数量
      this.updateRecipientCount();
    },

    // 恢复联系人选择状态
    restoreContactSelection() {
      console.log('restoreContactSelection 被调用');
      console.log('当前selectedContacts:', this.selectedContacts);
      console.log('当前contactList:', this.contactList);
      console.log('contactTable ref:', this.$refs.contactTable);
      
      if (!this.$refs.contactTable) {
        console.log('表格引用不存在，跳过恢复');
        return;
      }
      
      if (this.selectedContacts.length === 0) {
        console.log('没有已选择的联系人，跳过恢复');
        return;
      }

      // 先清除当前表格选择，防止冲突
      this.$refs.contactTable.clearSelection();

      // 使用 $nextTick 确保表格已经渲染
      this.$nextTick(() => {
        // 根据已选择的联系人ID来恢复表格选择状态
        this.contactList.forEach(contact => {
          const isSelected = this.selectedContacts.some(selected =>
            selected.customerId === contact.customerId
          );
          console.log(`联系人 ${contact.customerName} (ID: ${contact.customerId}) 是否已选择:`, isSelected);
          if (isSelected) {
            this.$refs.contactTable.toggleRowSelection(contact, true);
          }
        });
        console.log('恢复选择状态完成');
      });
    },
    confirmContactSelection() {
      this.contactDialogVisible = false;
      this.recipientCount = this.selectedContacts.length;
      this.$message.success(`已选择 ${this.selectedContacts.length} 个联系人`);
      
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.messageForm.validateField('recipients');
      });
    },

    // 验证接收人
    validateRecipients(rule, value, callback) {
      if (this.messageForm.recipientType === 'group') {
        if (this.selectedContacts.length === 0) {
          callback(new Error('请选择接收人'));
          return;
        }
        callback();
      } else if (this.messageForm.recipientType === 'upload') {
        if (this.uploadedEmails.length === 0) {
          callback(new Error('请导入接收人邮箱'));
        } else {
          callback();
        }
      } else if (this.messageForm.recipientType === 'manual') {
        const emails = this.manualRecipients.split(/[\n,]+/).filter(email => email.trim());
        if (emails.length === 0) {
          callback(new Error('请输入有效的接收人邮箱'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },

    // 历史任务相关方法
    showHistoryDialog() {
      this.historyDialogVisible = true;
      this.getHistoryList();
    },
    getHistoryList() {
      this.historyLoading = true;
      this.historyQueryParams.createUserid = this.$store.getters.userId;
      listEmailTask(this.historyQueryParams).then(response => {
        this.historyList = response.rows;
        this.historyTotal = response.total;
        this.historyLoading = false;
      });
    },
    resetHistoryQuery() {
      this.historyQueryParams = {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        createUserid: null
      };
      this.getHistoryList();
    },
    loadHistoryTask(row) {
      getEmailTask(row.taskId).then(response => {
        const task = response.data;

        // 设置基本信息
        this.messageForm.taskName = task.taskName;
        this.messageForm.emailSenderId = task.emailSenderId;
        this.messageForm.emailSubject = task.emailSubject;
        this.messageForm.emailContent = task.emailContent;
        this.messageForm.attachments = task.attachments ? JSON.parse(task.attachments) : [];

        // 处理模板信息
        if (task.templateId) {
          this.messageForm.templateId = task.templateId;

          // 如果模板列表还没有加载，先加载模板列表
          if (this.templateDialogList.length === 0) {
            this.getTemplateList().then(() => {
              // 在模板列表加载完成后查找模板名称
              const template = this.templateDialogList.find(t => t.materialId === task.templateId);
              if (template) {
                this.selectedTemplateName = template.templateName;
              }
            });
          } else {
            // 直接从已有的模板列表中查找
            const template = this.templateDialogList.find(t => t.materialId === task.templateId);
            if (template) {
              this.selectedTemplateName = template.templateName;
            }
          }
        } else {
          this.messageForm.templateId = '';
          this.selectedTemplateName = '';
        }

        // 设置接收人信息
        this.selectedContacts = task.recipients || [];
        this.recipientCount = this.selectedContacts.length;

        // 处理定时发送设置
        if (task.scheduledTime) {
          this.sendType = 'timed';
          this.messageForm.scheduledTime = task.scheduledTime;
        } else {
          this.sendType = 'timed';
          this.initScheduledTime();
        }

        this.historyDialogVisible = false;
        this.$message.success('历史任务加载成功');
      }).catch(error => {
        console.error('加载历史任务失败:', error);
        this.$message.error('加载历史任务失败，请稍后重试');
      });
    },
    copyHistoryTask(row) {
      getEmailTask(row.taskId).then(response => {
        const task = response.data;

        this.messageForm.templateId=task.templateId;
        // 设置基本信息（复制任务时修改任务名称）
        this.messageForm.taskName = `${task.taskName}_复制`;
        this.messageForm.emailSenderId = task.emailSenderId;
        this.messageForm.emailSubject = task.emailSubject;
        this.messageForm.emailContent = task.emailContent;
        this.messageForm.attachments = task.attachments ? JSON.parse(task.attachments) : [];

        // 处理模板信息
        if (task.templateId) {
          this.messageForm.templateId = task.templateId;

          // 如果模板列表还没有加载，先加载模板列表
          if (this.templateDialogList.length === 0) {
            this.getTemplateList().then(() => {
              // 在模板列表加载完成后查找模板名称
              const template = this.templateDialogList.find(t => t.materialId === task.templateId);
              if (template) {
                this.selectedTemplateName = template.templateName;
              }
            });
          } else {
            // 直接从已有的模板列表中查找
            const template = this.templateDialogList.find(t => t.materialId === task.templateId);
            if (template) {
              this.selectedTemplateName = template.templateName;
            }
          }
        } else {
          this.messageForm.templateId = '';
          this.selectedTemplateName = '';
        }

        // 设置接收人信息
        this.selectedContacts = task.recipients || [];
        this.recipientCount = this.selectedContacts.length;

        // 处理定时发送设置
        if (task.scheduledTime) {
          this.sendType = 'timed';
          this.messageForm.scheduledTime = task.scheduledTime;
        } else {
          this.sendType = 'timed';
          this.initScheduledTime();
        }

        this.historyDialogVisible = false;
        this.$message.success('任务复制成功');
      }).catch(error => {
        console.error('复制任务失败:', error);
        this.$message.error('复制任务失败，请稍后重试');
      });
    },

    // 状态相关方法
        getStatusType(status) {
          const statusMap = { '0': 'info', '1': 'primary', '2': 'warning', '3': 'success','4': 'danger' };
          return statusMap[status] || 'info';
        },
        getStatusText(status) {
          const statusMap = { '0': '草稿', '1': '待发送', '2': '发送中', '3': '已完成', '4': '已取消', };
          return statusMap[status] || '未知';
        }
  },
  watch: {
    'messageForm.recipientGroup': 'updateRecipientCount',
    'manualRecipients': 'updateRecipientCount',
    'selectedContacts': 'updateRecipientCount'
  }
};
</script>

<style scoped>
/* Add styles similar to SmsMassMessaging.vue but for email */
.email-mass-messaging-container { padding: 0px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.header-title { font-size: 16px; font-weight: 600; }
.template-selector { display: flex; gap: 10px; }
.recipient-info { margin-top: 10px; color: #909399; font-size: 14px; }
.recipient-info .count { color: #409EFF; font-weight: bold; }

/* 发送统计样式 */
.send-stats-card {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.stats-header {
  background-color: #fff;
  padding: 12px 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: #495057;
}

.stats-header i {
  color: #409EFF;
  font-size: 16px;
}

.stats-content {
  padding: 16px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.stat-row:last-child {
  margin-bottom: 0;
}

.stat-row.total {
  border-top: 1px solid #e9ecef;
  padding-top: 12px;
  margin-top: 8px;
  font-weight: 600;
}

.stat-label {
  color: #6c757d;
  font-size: 14px;
}

.stat-value {
  font-weight: 600;
  font-size: 16px;
  color: #212529;
}

.stat-value.price {
  color: #409EFF;
}

.stat-value.price-total {
  color: #dc3545;
  font-size: 18px;
  font-weight: 700;
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  gap: 10px;
}

.timed-send-btn {
  flex: 1;
  height: 44px;
  font-size: 14px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.timed-send-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.draft-btn {
  flex: 1;
  height: 44px;
  font-size: 14px;
  font-weight: 600;
  border-radius: 8px;
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
  transition: all 0.3s ease;
}

.draft-btn:hover {
  background-color: #e9ecef;
  border-color: #adb5bd;
  transform: translateY(-1px);
}

.stat-number {
  font-weight: bold;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.error {
  color: #f56c6c;
}

/* 最近发送记录样式 */
.history-card {
  margin-top: 20px;
}

.history-list .el-table {
  border: none;
}

.history-item {
  padding: 5px 0;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.history-info {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

/* 联系人选择相关样式 */
.selected-contacts-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.more-contacts {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

/* 统一的el-tree样式 */
.group-tree-card .el-tree {
  background-color: transparent;
}

.group-tree-card .el-tree-node {
  margin-bottom: 4px;
}

.group-tree-card >>> .el-tree-node__content {
  height: 36px !important;
  line-height: 36px !important;
  min-height: 36px !important;
  padding: 0 10px 0 0 !important;
}

.group-tree-card .el-tree-node__expand-icon {
  padding: 6px;
}

.group-tree-card .el-tree-node__label {
  font-size: 14px;
}

.group-tree-card .el-card__body {
  padding: 20px;
}

.contact-list-card .el-card__body {
  padding: 20px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
}

.node-label {
  display: flex;
  align-items: center;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 发件箱选择样式 */
.sender-option {
  display: flex;
  flex-direction: column;
  line-height: 1.2;
}

.sender-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.sender-email {
  color: #909399;
  font-size: 12px;
  margin-top: 2px;
}
</style>
